package com.example.screenrecorder;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import java.io.File;

/**
 * 测试Activity - 用于调试录制功能
 * 检查权限状态、存储空间、文件路径等
 */
public class TestActivity extends AppCompatActivity {
    
    private static final String TAG = "TestActivity";
    private TextView tvStatus;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        
        tvStatus = findViewById(R.id.tv_status);
        
        // 执行所有检查
        performAllChecks();
    }
    
    /**
     * 执行所有检查项目
     */
    private void performAllChecks() {
        StringBuilder status = new StringBuilder();
        status.append("=== 屏幕录制功能检查 ===\n\n");
        
        // 检查权限
        status.append("1. 权限检查:\n");
        status.append(checkPermissions());
        status.append("\n");
        
        // 检查存储
        status.append("2. 存储检查:\n");
        status.append(checkStorage());
        status.append("\n");
        
        // 检查系统版本
        status.append("3. 系统版本:\n");
        status.append(checkSystemVersion());
        status.append("\n");
        
        // 检查文件路径
        status.append("4. 文件路径检查:\n");
        status.append(checkFilePaths());
        status.append("\n");
        
        tvStatus.setText(status.toString());
        
        // 输出到日志
        Log.d(TAG, status.toString());
    }
    
    /**
     * 检查权限状态
     */
    private String checkPermissions() {
        StringBuilder result = new StringBuilder();
        
        // 检查音频权限
        boolean audioPermission = ContextCompat.checkSelfPermission(this, 
            Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
        result.append("  音频录制权限: ").append(audioPermission ? "✅" : "❌").append("\n");
        
        // 检查存储权限
        boolean storagePermission = ContextCompat.checkSelfPermission(this, 
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        result.append("  存储权限: ").append(storagePermission ? "✅" : "❌").append("\n");
        
        // 检查通知权限
        boolean notificationPermission = ContextCompat.checkSelfPermission(this, 
            Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
        result.append("  通知权限: ").append(notificationPermission ? "✅" : "❌").append("\n");
        
        // 检查摄像头权限
        boolean cameraPermission = ContextCompat.checkSelfPermission(this, 
            Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        result.append("  摄像头权限: ").append(cameraPermission ? "✅" : "❌").append("\n");
        
        // 检查悬浮窗权限
        boolean overlayPermission = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            overlayPermission = android.provider.Settings.canDrawOverlays(this);
        }
        result.append("  悬浮窗权限: ").append(overlayPermission ? "✅" : "❌").append("\n");
        
        return result.toString();
    }
    
    /**
     * 检查存储状态
     */
    private String checkStorage() {
        StringBuilder result = new StringBuilder();
        
        try {
            // 检查外部存储是否可用
            boolean externalStorageAvailable = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);
            result.append("  外部存储可用: ").append(externalStorageAvailable ? "✅" : "❌").append("\n");
            
            if (externalStorageAvailable) {
                // 检查Movies目录
                File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
                result.append("  Movies目录: ").append(moviesDir.getAbsolutePath()).append("\n");
                result.append("  Movies目录存在: ").append(moviesDir.exists() ? "✅" : "❌").append("\n");
                
                // 检查ScreenRecord目录
                File screenRecordDir = new File(moviesDir, "ScreenRecord");
                result.append("  ScreenRecord目录: ").append(screenRecordDir.getAbsolutePath()).append("\n");
                result.append("  ScreenRecord目录存在: ").append(screenRecordDir.exists() ? "✅" : "❌").append("\n");
                
                // 尝试创建目录
                if (!screenRecordDir.exists()) {
                    boolean created = screenRecordDir.mkdirs();
                    result.append("  创建ScreenRecord目录: ").append(created ? "✅" : "❌").append("\n");
                }
                
                // 检查可用空间
                long freeSpace = moviesDir.getFreeSpace();
                long totalSpace = moviesDir.getTotalSpace();
                result.append("  可用空间: ").append(formatBytes(freeSpace)).append("\n");
                result.append("  总空间: ").append(formatBytes(totalSpace)).append("\n");
                result.append("  空间充足: ").append(freeSpace > 100 * 1024 * 1024 ? "✅" : "❌").append("\n");
            }
            
        } catch (Exception e) {
            result.append("  存储检查出错: ").append(e.getMessage()).append("\n");
            Log.e(TAG, "Storage check error", e);
        }
        
        return result.toString();
    }
    
    /**
     * 检查系统版本
     */
    private String checkSystemVersion() {
        StringBuilder result = new StringBuilder();
        
        result.append("  Android版本: ").append(Build.VERSION.RELEASE).append("\n");
        result.append("  API级别: ").append(Build.VERSION.SDK_INT).append("\n");
        result.append("  最低要求: API 24 (Android 7.0)\n");
        result.append("  版本兼容: ").append(Build.VERSION.SDK_INT >= 24 ? "✅" : "❌").append("\n");
        
        return result.toString();
    }
    
    /**
     * 检查文件路径
     */
    private String checkFilePaths() {
        StringBuilder result = new StringBuilder();
        
        try {
            // 测试文件路径创建
            File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            File screenRecordDir = new File(moviesDir, "ScreenRecord");
            
            if (!screenRecordDir.exists()) {
                screenRecordDir.mkdirs();
            }
            
            // 创建测试文件
            File testFile = new File(screenRecordDir, "test_file.txt");
            boolean canWrite = testFile.createNewFile();
            result.append("  测试文件创建: ").append(canWrite ? "✅" : "❌").append("\n");
            
            if (canWrite) {
                // 删除测试文件
                testFile.delete();
                result.append("  测试文件清理: ✅\n");
            }
            
            result.append("  录制目录: ").append(screenRecordDir.getAbsolutePath()).append("\n");
            
        } catch (Exception e) {
            result.append("  文件路径检查出错: ").append(e.getMessage()).append("\n");
            Log.e(TAG, "File path check error", e);
        }
        
        return result.toString();
    }
    
    /**
     * 格式化字节数
     */
    private String formatBytes(long bytes) {
        if (bytes < 1024) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String pre = "KMGTPE".charAt(exp - 1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
    }
}
